use crate::core::config::Conf;
use log::{LevelFilter};
use log4rs::{
    append::{
        console::{ConsoleAppender, Target},
        file::FileAppender,
    },
    config::{Appender, Config, Root},
    encode::pattern::PatternEncoder,
    filter::threshold::ThresholdFilter,
};

pub fn init_with_config(conf : &Conf) {
    let log_patten = "{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}";
    let file_path = conf.log.to_owned();
    let level = match conf.log_lvl.as_ref() {
        "error" => LevelFilter::Error,
        "warn"  => LevelFilter::Warn,
        "trace" => LevelFilter::Trace,
        "info"  => LevelFilter::Info,
        "debug" => LevelFilter::Debug,
              _ => LevelFilter::Info
    };
    
    let stderr = ConsoleAppender::builder()
        .encoder(Box::new(PatternEncoder::new(log_patten)))
        .target(Target::Stderr).build();
    let logfile = FileAppender::builder()
        //Pattern https://docs.rs/log4rs/*/log4rs/encode/pattern/index.html
        .encoder(Box::new(PatternEncoder::new(log_patten)))
        .build(file_path)
        .unwrap();

    let config = Config::builder()
        .appender(
            Appender::builder()
                .filter(Box::new(ThresholdFilter::new(level)))
                .build("logfile", Box::new(logfile)))
        .appender(
            Appender::builder()
                .filter(Box::new(ThresholdFilter::new(level)))
                .build("stderr", Box::new(stderr)),
        )
        .build(
            Root::builder()
                .appender("logfile")
                .appender("stderr")
                .build(level),
        )
        .unwrap();

    log4rs::init_config(config).unwrap();

}